package net.ufrog.common.converters;

import java.math.BigDecimal;

/**
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-07-04
 * @since 0.1
 */
public class IntegerConverter extends Converter<Integer> {

    @Override
    public Integer convert(Object obj, Object defaultValue) {
        if (obj != null) {
            return toInteger(obj);
        } else if (defaultValue != null) {
            return toInteger(defaultValue);
        } else {
            return null;
        }
    }

    @Override
    public Class<Integer> getType() {
        return Integer.class;
    }

    private Integer toInteger(Object obj) {
        if (obj instanceof Number) {
            return Number.class.cast(obj).intValue();
        } else {
            return new BigDecimal(String.valueOf(obj)).intValue();
        }
    }
}
